import { mapState, mapActions, mapMutations } from "vuex";
export default {
  props: ["chapter_obj", "teacher_obj"],
  components: {},
  data() {
    return {
      rtc_info: {
        userName:
          this.$store.state.user_info.acName ||
          this.$store.state.user_info.email,
        publisherList: [],
        userList: [],
        streamstate: "",
        streamAction: ""
      },
      // channelId: 'aaat', //房间号
      offsetLeft: 0,
      userId: "",
      is_publish_audio: true, //是否推送音频 (本地)
      is_publish_camera: true, //是否推送视频 (本地)
      is_publish_screen: true, //是否推送屏幕录制 (本地)
      is_join_channel: false, //是否加入了直播间
      is_camera_extended: false, //是否将摄像移动主面板
      is_show_controls: false, //是否显示操作面板
      is_subscribed_teacher: false, //是否订阅老师
      is_mute_volume: false, //是否禁音
      is_full_screen: false, //视频全屏
      is_extend_subScreen: false, //主副屏切换
      is_share_screen: false, //共享流是否开启 (远程端)
      is_share_video: false, //视频流是否开启 (远程端)
      is_share_audio: false, //音频流是否开启(远程端)
      is_proccesing: false, //处理中
      streamAction: "",
      streamstate: "",
      publish_failed_time: 0, //推流失败计数
      main_screen_failed_time: 0, //订阅老师主屏失败计数
      streamlist_failed_time: 0, //获取流失败次数
      timeout: null, //防抖函数计时器
      timer: null, //全屏事件监听定时器
      env_support: {
        audioDevice: true, //	音频设备是否可用
        browser: "", //浏览器名称
        browser_version: "9", //浏览器版本
        isElectron: false,
        isSupported: true, //是否支持webRTC
        supportH264: true, //是否支持H264
        supportScreenShare: true, //是否支持屏幕分享
        system: "",
        videoDevice: true //摄像头是否可用
      } //兼容情况
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      token(state) {
        return state.token;
      },
      is_ios(state) {
        return state.is_ios;
      },
      sys_rtc_info(state) {
        return state.rtc_info;
      }
    })
  },
  watch: {
    chapter_obj: {
      handler(a, b, c) {
        const video = this.$refs.rtcVideo;
        aliWebrtc.leaveChannel();
        aliWebrtc.dispose();
        video.removeEventListener(
          "webkitfullscreenchange",
          this.onFullscreenChange
        );
        video.removeEventListener("fullscreenchange", this.onFullscreenChange);
        this.initState();
        this.$nextTick(() => {
          this.startRTC();
        });
      },
      deep: true // 必须加这个属性
    },
    is_share_screen(new_val, old_val) {
      if (new_val != old_val) {
        if (this.is_extend_subScreen) {
          this.is_extend_subScreen = false;
        }
        this.getTeacherVideo();
      }
    },
    is_share_video(new_val, old_val) {
      if (new_val != old_val) {
        if (this.is_extend_subScreen) {
          this.is_extend_subScreen = false;
        }
        this.getTeacherVideo();
      }
    },
    is_share_audio(new_val, old_val) {
      if (new_val != old_val) {
        this.getTeacherVideo();
      }
    }
  },
  activated() {
    this.$nextTick(() => {
      if (process.client) {
        this.startRTC();
        window.onbeforeunload = function(e) {
          if (!aliWebrtc) {
            console.log("isSupport失败,未能初始化aliWebrtc", "danger");
            return;
          }
          aliWebrtc.leaveChannel();
          aliWebrtc.dispose();
        };
      }
    });
  },
  deactivated() {
    console.log("重载直播间");
    aliWebrtc.leaveChannel();
    aliWebrtc.dispose();
    this.initState();
  },
  destroyed() {
    console.log("离开直播间");
    aliWebrtc.leaveChannel();
    aliWebrtc.dispose();
    this.initState();
  },
  methods: {
    initState() {
      this.rtc_info = {
        userName:
          this.$store.state.user_info.acName ||
          this.$store.state.user_info.email,
        publisherList: [],
        userList: [],
        streamstate: "",
        streamAction: ""
      };
      this.offsetLeft = 0;
      this.userId = "";
      this.is_publish_audio = true; //是否推送音频
      this.is_publish_camera = true; //是否推送视频
      this.is_publish_screen = true; //是否推送屏幕录制
      this.is_join_channel = false; //是否加入了直播间
      this.is_show_controls = false; //是否显示操作面板
      this.is_subscribed_teacher = false; //是否订阅老师
      this.is_mute_volume = false; //是否禁音
      this.is_full_screen = false; //视频全屏
      this.is_extend_subScreen = false;
      this.is_share_screen = false; //共享流是否开启 (远程端)
      this.is_share_video = false; //视频流是否开启 (远程端)
      this.is_share_audio = false; //音频流是否开启(远程端)
      this.is_proccesing = false; //处理中
      this.streamAction = "";
      this.streamstate = "";
      this.publish_failed_time = 0; //推流失败计数
      this.main_screen_failed_time = 0; //订阅老师主屏失败计数
      this.streamlist_failed_time = 0; //获取流失败次数
      this.timeout = null; //防抖函数计时器
      this.timer = null;
      this.env_support = {
        audioDevice: true, //	音频设备是否可用
        browser: "", //浏览器名称
        browser_version: "9", //浏览器版本
        isElectron: false,
        isSupported: true, //是否支持webRTC
        supportH264: true, //是否支持H264
        supportScreenShare: true, //是否支持屏幕分享
        system: "",
        videoDevice: true //摄像头是否可用
      }; //兼容情况
    },
    //判断是否订阅推流用户  任一视频还是音频流订阅都算订阅了
    is_subscribed(item) {
      if (!item) {
        return false;
      } else {
        const { streamConfigs } = item;
        if (!streamConfigs) {
          return false;
        } else {
          if (streamConfigs.length > 0) {
            let stream_subscribed_list = streamConfigs.filter(
              i => i.subscribed
            );
            if (stream_subscribed_list.length > 0) {
              return true;
            } else {
              return false;
            }
          } else {
            return false;
          }
        }
      }
    },
    //判断是否订阅了音频
    is_audio_subscribed(item) {
      if (!item) {
        return false;
      } else {
        const { streamConfigs } = item;
        if (!streamConfigs) {
          return false;
        } else {
          if (streamConfigs.length > 0) {
            let stream_subscribed = streamConfigs.filter(
              i => i.label == "sophon_audio"
            )[0].subscribed;
            return stream_subscribed;
          } else {
            return false;
          }
        }
      }
    },
    //判断是否订阅了视频
    is_camera_subscribed(item) {
      if (!item) {
        return false;
      } else {
        const { streamConfigs } = item;
        if (!streamConfigs) {
          return false;
        } else {
          if (streamConfigs.length > 0) {
            let stream_subscribed = streamConfigs.filter(
              i => i.label == "sophon_video_camera_large"
            )[0].subscribed;
            return stream_subscribed;
          } else {
            return false;
          }
        }
      }
    },
    //判断是否订阅了屏幕分享
    is_screen_subscribed(item) {
      if (!item) {
        return false;
      } else {
        const { streamConfigs } = item;
        if (!streamConfigs) {
          return false;
        } else {
          if (streamConfigs.length > 0) {
            let stream_subscribed = streamConfigs.filter(
              i => i.label == "sophon_video_screen_share"
            )[0].subscribed;
            return stream_subscribed;
          } else {
            return false;
          }
        }
      }
    },
    async checkEnv() {
      return new Promise((res, rej) => {
        const { audioDevice, videoDevice, isSupported } = this.env_support;
        if (!isSupported) {
          if (this.is_mobile) {
            this.$dialog
              .alert({
                title: "提示",
                message: "当前环境不支持小班课"
              })
              .then(() => {
                // on close
              });
          } else {
            this.$Modal.warning({
              title: "提示",
              content: "当前环境不支持小班课",
              okText: "确定",
              maskClosable: false,
              closable: false
            });
          }
          rej();
        } else {
          if (!audioDevice || !videoDevice) {
            if (this.is_mobile) {
              this.$dialog
                .alert({
                  title: "提示",
                  message: "当前环境不支持媒体录制",
                  showConfirmButton: false
                })
                .then(() => {
                  // on close
                });
            } else {
              this.$Modal.warning({
                title: "提示",
                content: "当前环境不支持媒体录制",
                okText: "确定",
                maskClosable: false,
                closable: false
              });
            }
          }
          res();
        }
      });
    },
    startRTC() {
      if (process.client) {
        window.aliWebrtc = new AliRtcEngine();
        console.log(aliWebrtc);
        aliWebrtc
          .isSupport({
            isDebug: process.env.NODE_ENV === "development" ? true : false
          })
          .then(re => {
            this.env_support = {
              ...re
            };
            this.checkEnv().then(() => {
              this.initRTC();
            });
          })
          .catch(error => {
            console.warn(error);
            // this.$message.error(error.message);
          });
      }
    },
    initRTC() {
      const { publisherList, userList } = this.rtc_info;
      console.log("aliWebrtc", aliWebrtc);
      aliWebrtc.on("onJoin", publisher => {
        console.log("onJoin:", publisher);
        if (publisher.userId) {
          this.updateUserList();
        }
        //重置订阅状态
        //默认订阅远端音频和视频大流，但需要调用subscribe才能生效
        //这里取消默认订阅，根据需求进行订阅
        // aliWebrtc.configRemoteAudio(publisher.userId, false);
        // aliWebrtc.configRemoteCameraTrack(publisher.userId, false, false);
        // this.$message.success(publisher.displayName + "加入房间","success");
        console.log(publisher.displayName + "加入房间");
      });

      aliWebrtc.on("onPublisher", publisher => {
        console.log("onPublisher", publisher);
        let index = userList.filter(i => i.userId == publisher.userId);
        if (index.length == 0) {
          //新增
          // this.rtc_info.publisherList = [...publisherList, publisher];
          this.updateUserList();
        } else {
          //流状态更新
          console.log("流状态更新");
          this.updateUserList();
          // this.updatePublisherStream(publisher, index);
        }
      });

      aliWebrtc.on("onUnPublisher", publisher => {
        console.log("onUnPublisher", publisher);
        this.updateUserList();
        // this.detelePublisher(publisher.userId);
        // initialization(publisher.userId);
      });
      aliWebrtc.on("onNotify", data => {
        console.log("onNotify:", data);
      });
      aliWebrtc.on("onUpdateRole", data => {
        console.log("onUpdateRole:", data);
      });
      aliWebrtc.on("onBye", message => {
        console.log("onBye", message);
        //1:被服务器踢出
        //2:频道关闭
        //3:同一个ID在其他端登录,被服务器踢出
        var msg;
        switch (message.code) {
          case 1:
            msg = "被服务器踢出";
            break;
          case 2:
            msg = "频道关闭";
            break;
          case 3:
            msg = "同一个ID在其他端登录,被服务器踢出";
            break;
          default:
            msg = "onBye";
        }
        this.$Message.success(msg);
        // this.is_join_channel = false;
      });

      aliWebrtc.on("onError", error => {
        console.log("错误！！！！！！！");
        console.log(error);
        var msg = error && error.message ? error.message : error;
        if (msg && msg.indexOf("no session") > -1) {
          msg = "请重新登录：" + msg;
        }
        if (error.errorCode === 10011 || error.errorCode === 10012) {
          msg = error.errorCode === 10011 ? "屏幕共享被禁止" : "屏幕共享已取消";
          setTimeout(() => {
            this.getPublishState("danger");
          }, 2000);
        }

        if (error.code == 15) {
          msg = "没有开启H5兼容";
        }
        if (error.type === "publish") {
          // 提示用户网络状态不佳
          console.log("推流断开 需要停止推流,然后重新推流");
          // 先记录当前推流状态
          var pubAudio = aliWebrtc.configLocalAudioPublish;
          var pubCamera = aliWebrtc.configLocalCameraPublish;
          var pubScreen = aliWebrtc.configLocalScreenPublish;
          // 设置取消推流
          aliWebrtc.configLocalAudioPublish = false;
          aliWebrtc.configLocalCameraPublish = false;
          aliWebrtc.configLocalScreenPublish = false;

          this.is_publish_audio = aliWebrtc.configLocalAudioPublish;
          this.is_publish_camera = aliWebrtc.configLocalCameraPublish;
          this.is_publish_screen = aliWebrtc.configLocalScreenPublish;

          aliWebrtc
            .publish()
            .then(() => {
              console.log("推流断开取消推流成功");
              aliWebrtc.configLocalAudioPublish = pubAudio;
              aliWebrtc.configLocalCameraPublish = pubCamera;
              aliWebrtc.configLocalScreenPublish = pubScreen;

              this.is_publish_audio = aliWebrtc.configLocalAudioPublish;
              this.is_publish_camera = aliWebrtc.configLocalCameraPublish;
              this.is_publish_screen = aliWebrtc.configLocalScreenPublish;

              aliWebrtc
                .publish()
                .then(() => {
                  console.log("推流断开重新推流成功");
                })
                .catch(err => {
                  console.log("推流断开重新推流失败");
                });
            })
            .catch(err => {
              console.log("推流断开取消推流失败");
            });
        }
        if (error.type === "subscribe") {
          console.log(
            "订阅断开 取消订阅该userId的所有订阅并移除所有该userId的dom"
          );
          //先记录当前用户的订阅状态
          var subInfo = getSubscribeInfo(error.userId);
          //取消订阅状态
          initialization(error.userId);
          aliWebrtc
            .subscribe(error.userId)
            .then(re => {
              console.log("订阅断开 取消订阅成功");
              aliWebrtc.configRemoteAudio(error.userId, subInfo.isSubAudio);
              aliWebrtc.configRemoteCameraTrack(
                error.userId,
                subInfo.isSubLarge,
                subInfo.isSubCamera
              );
              aliWebrtc.configRemoteScreenTrack(
                error.userId,
                subInfo.isSubScreen
              );
              aliWebrtc
                .subscribe(error.userId)
                .then(re => {
                  console.log("订阅断开 重新订阅成功");
                  // if ($('#' + error.userId + '_camera')) {
                  //     aliWebrtc.setDisplayRemoteVideo(error.userId, $('#' + error.userId + '_camera video')[0], 1);
                  // }
                  // if ($('#' + error.userId + '_screen')) {
                  //     aliWebrtc.setDisplayRemoteVideo(error.userId, $('#' + error.userId + '_screen video')[0], 2);
                  // }
                })
                .catch(err => {
                  console.log("订阅断开 重新订阅失败");
                  this.detelePublisher(error.userId);
                });
            })
            .catch(err => {
              console.log("订阅断开 取消订阅失败", err);
              this.detelePublisher(error.userId);
            });
        }
        // this.$message.success(msg, "danger");
        console.log("danger:", msg);
      });

      aliWebrtc.on("onLeave", publisher => {
        // initialization(publisher.userId);
        this.updateUserList();
        // this.$Message.success(publisher.displayName + "离开房间", "success");
      });
      aliWebrtc.on("onMediaStream", (subscriber, stream) => {
        console.log("onMediaStream:", subscriber, stream);
        // var video = document.getElementByTag('video');
        // aliWebrtc.setDisplayRemoteVideo(
        //     subscriber, // onMediaStream中返回的参数
        //     video, // html中用于显示stream对象的video元素
        //     stream // onMediaStream中返回的参数
        // );
      });
      this.$nextTick(() => {
        // this.joinroom();
        // var localVideo = this.$refs.rtcVideo;
        // aliWebrtc
        //   .startPreview(localVideo)
        //   .then(obj => {
        //     // this.selfVideo = this.$refs.selfVideo;
        //     // aliWebrtc.configLocalScreenPublish = true;
        //     // this.rePublish();
        //   })
        //   .catch(error => {
        //     // showAlert('[开启预览失败]' + error.message, 'danger');
        //     console.warn("[开启预览失败]" + error.message, "danger");
        //   });
      });
    },
    //更新在綫用戶列表
    updateUserList() {
      // const { aliWebrtc, userList } = this.rtc_info;
      let _userList = aliWebrtc.getUserList();
      console.log("_userList:", _userList);
      this.rtc_info.userList = _userList;

      //更新主播流状态改变后的视频窗口

      const user_list = this.rtc_info.userList;
      let observer;
      //超管流
      let admin_observer = user_list.filter(i => /admin/.test(i.userId));
      //教师流
      let teacher_observer = user_list.filter(
        i => i.userId == this.teacher_obj.id
      );
      //管理员开播订阅管理员 其次是课程老师
      if (admin_observer.length > 0) {
        observer = admin_observer ? admin_observer[0] : null;
        // this.rtc_info.publisherList = [
        //   ...this.rtc_info.publisherList,
        //   observer
        // ];
      } else if (teacher_observer.length > 0) {
        observer = teacher_observer ? teacher_observer[0] : null;
        // this.rtc_info.publisherList = [
        //   ...this.rtc_info.publisherList,
        //   observer
        // ];
      } else {
        observer = null;
      }
      console.log("observer:", observer);
      if (observer) {
        let screen_share_result = observer.streamConfigs.filter(
          i => i.label == "sophon_video_screen_share" && i.state == "active"
        );
        let video_share_result = observer.streamConfigs.filter(
          i => i.label == "sophon_video_camera_large" && i.state == "active"
        );
        let audio_share_result = observer.streamConfigs.filter(
          i => i.label == "sophon_audio" && i.state == "active"
        );
        if (screen_share_result.length > 0) {
          this.is_share_screen = true;
        } else {
          this.is_share_screen = false;
        }
        if (video_share_result.length > 0) {
          this.is_share_video = true;
        } else {
          this.is_share_video = false;
        }
        if (audio_share_result.length > 0) {
          this.is_share_audio = true;
        } else {
          this.is_share_audio = false;
        }
      } else {
        this.is_share_screen = false;
        this.is_share_video = false;
        this.is_share_audio = false;
      }
    },
    updatePublisherStream(publisher, index) {
      const { publisherList } = this.rtc_info;
      let oldStreamConfigs = JSON.parse(
        JSON.stringify(publisherList[index].streamConfigs)
      );
      let newStreamConfigs = publisher.streamConfigs;
      let subscribeInfo = getSubscribeInfo(publisher.userId);
      oldStreamConfigs.forEach((v, i, a) => {
        let newStream = newStreamConfigs.getObjByProprety(v.label, "label");
        // 判断流状态改变了 但不确定我们是否订阅了该流
        if (v.state != newStream.state) {
          console.log(
            "流的状态变了" + v.label,
            v,
            v.type,
            ">" + v.state + ">>" + newStream.state + ">",
            newStream,
            subscribeInfo
          );
          //并且要取消订阅某个流，不然就不能再次订阅了
          subscribeInfo.subscribeInfoArr.forEach(sv => {
            if (v.label === sv.label) {
              console.log(
                "setConfigRemote取消订阅调用[api]:subscribe",
                publisher.userId,
                sv.type,
                sv.label
              );
              this.setConfigRemote(publisher.userId, sv.type, sv.label)
                .then(re => {
                  // 移除dom
                  // removeDom(publisher.userId, v.label);
                })
                .catch(error => {
                  console.error("流的状态变了重新订阅出问题", error);
                });
            }
          });
        }
      });
      this.rtc_info.publisherList = publisherList.splice(index, 1, publisher);
    },
    setConfigRemote(userId, label) {
      // const { aliWebrtc } = this.rtc_info;
      return new Promise((resolve, reject) => {
        //demo中只订阅大流
        if (label === "sophon_video_camera_large") {
          aliWebrtc.configRemoteCameraTrack(userId, false, false);
          aliWebrtc.configRemoteAudio(userId, false);
        } else if (label === "sophon_video_screen_share") {
          aliWebrtc.configRemoteScreenTrack(userId, false);
        }
        aliWebrtc
          .subscribe(userId)
          .then(re => {
            console.log("订阅成功：", re);
            resolve();
          })
          .catch(error => console.log("取消订阅失败", error));
      });
    },
    //订阅流更改
    resetConfigRemote(type, item) {
      const { userId, streamConfigs } = item;
      let audio_stream = streamConfigs.filter(i => i.label == "sophon_audio")[0]
        .subscribed;
      let video_stream = streamConfigs.filter(
        i => i.label == "sophon_video_camera_large"
      )[0].subscribed;
      let screen_stream = streamConfigs.filter(
        i => i.label == "sophon_video_screen_share"
      )[0].subscribed;
      if (type == "camera") {
        aliWebrtc.configRemoteCameraTrack(userId, !video_stream, !video_stream);
        aliWebrtc.configRemoteAudio(userId, audio_stream);
      } else if (type == "audio") {
        aliWebrtc.configRemoteCameraTrack(userId, video_stream, video_stream);
        aliWebrtc.configRemoteAudio(userId, !audio_stream);
      }
      aliWebrtc
        .subscribe(userId)
        .then(re => {
          console.log("重新订阅成功：", re);
          this.updateUserList();
        })
        .catch(error => console.log("取消订阅失败", error));
    },
    detelePublisher(userId) {
      const { publisherList } = this.rtc_info;
      let index = publisherList.getIndexByProprety(userId, "userId");
      if (index != -1) {
        this.rtc_info.publisherList = publisherList.filer(
          (i, x) => x !== index
        );
        this.detelePublisher(userId);
      } else {
        console.log("未找到之前的推流数据"); //删除推流用户
      }
    },
    getPublishState(type) {
      // const { aliWebrtc } = this.rtc_info;
      if (
        aliWebrtc.configLocalAudioPublish ||
        aliWebrtc.configLocalCameraPublish ||
        aliWebrtc.configLocalScreenPublish
      ) {
        // $('.publisher .push-stream').text('停止推流');
        this.streamAction = "停止推流";
        if (
          aliWebrtc.configLocalScreenPublish &&
          aliWebrtc.configLocalCameraPublish
        ) {
          this.streamstate = "视频流 + 共享流";
        } else {
          if (aliWebrtc.configLocalScreenPublish) {
            this.streamstate = "共享流";
          } else if (aliWebrtc.configLocalCameraPublish) {
            this.streamstate = "视频流";
          }
        }
      } else {
        // $('.publisher .push-stream').text('开始推流');
        this.streamAction = "开始推流";
        this.streamstate = "当前未推流";
      }
      console.log("推流状态：" + this.streamstate, type);
    },
    //取消订阅
    cancelSubscribed(item) {
      const { userId, streamConfigs } = item;
      aliWebrtc.configRemoteCameraTrack(userId, false, false);
      aliWebrtc.configRemoteAudio(userId, false);
      aliWebrtc
        .subscribe(userId)
        .then(re => {
          console.log("取消订阅成功，", re);
          this.updateUserList();
        })
        .catch(error => console.log("取消订阅失败", error));
    },
    joinroom(callback) {
      // $('.local-display-name .username b').text(userName);
      // $('.local-display-name .channelid b').text(channelId);
      // $('.local-display-name .streamstate b').text('当前未推流');
      //1.预览
      // var localVideo = $('.local-video video');
      // const { aliWebrtc, publisherList } = this.rtc_info;
      // var localVideo = this.$refs.selfVideo;
      // aliWebrtc
      //     .startPreview(localVideo)
      //     .then(obj => {})
      //     .catch(error => {
      //         // showAlert('[开启预览失败]' + error.message, 'danger');
      //         console.warn('[开启预览失败]' + error.message, 'danger');
      //     });
      //2. 获取频道鉴权令牌参数 为了防止被盗用建议该方法在服务端获取
      this.main_screen_failed_time = 0;
      this.publish_failed_time = 0;
      this.streamlist_failed_time = 0;
      this.checkEnv().then(() => {
        if (!this.chapter_obj || !this.chapter_obj.id) {
          return;
        }
        this.is_proccesing = true;
        var authInfo = this.GenerateAliRtcAuthInfo(this.chapter_obj.id);
        //3. 加入房间 默认推音频视频流
        aliWebrtc
          .joinChannel(authInfo, this.user_info.acName)
          .then(() => {
            console.log("加入房间成功", "success");

            //渲染老师屏
            this.getTeacherVideo();

            // 4. 发布本地流
            aliWebrtc.configLocalAudioPublish = true;
            aliWebrtc.configLocalCameraPublish = true;
            this.rePublish();
          })
          .catch(error => {
            // showAlert('[加入房间失败]' + error.message, 'danger');
            console.log("[加入房间失败]" + error.message, "danger");
          });
      });
    },
    async getTeacherVideo() {
      //订阅老师
      if (this.main_screen_failed_time < 5) {
        if (this.teacher_obj && this.teacher_obj.id) {
          let user_list = await aliWebrtc.getUserList();
          console.log("user_list:", user_list);
          let observer;
          let admin_observer = user_list.filter(i => /admin/.test(i.userId));
          let teacher_observer = user_list.filter(
            i => i.userId == this.teacher_obj.id
          );
          //管理员开播订阅管理员 其次是课程老师
          if (admin_observer.length > 0) {
            observer = admin_observer ? admin_observer[0] : null;
          } else {
            observer = teacher_observer ? teacher_observer[0] : null;
          }
          if (!observer) {
            setTimeout(() => {
              if (this.main_screen_failed_time == 4) {
                if (this.is_mobile) {
                  this.$toast("当前课程老师未开播！");
                } else {
                  this.$Message.info("当前课程老师未开播！");
                }
                this.is_proccesing = false;
                this.stopLive();
              }
              this.main_screen_failed_time = this.main_screen_failed_time + 1;
              this.getTeacherVideo();
            }, 2000);
          } else {
            this.main_screen_failed_time = 0;
            this.is_subscribed_teacher = true;
            this.showUserMenu(observer);
          }
        }
      }
    },
    stopLive() {
      aliWebrtc
        .leaveChannel()
        .then(e => {
          console.log("离开直播间", e);
          this.is_join_channel = false;
          this.is_subscribed_teacher = false;
          this.is_mute_volume = false;
          this.is_proccesing = false;
          this.updateUserList();
        })
        .catch(e => {
          console.log("离开直播间失败！", e);
          this.is_proccesing = false;
        });
    },
    /*
     * 获取测试token
     * @param {*} channelId 频道号
     * @return {object} authinfo
     */
    GenerateAliRtcAuthInfo(channelId) {
      //   var appId = "oqksqgoy"; // 修改为自己的appid 该方案仅为开发测试使用，正式上线需要使用服务端的AppServer
      var appId = this.sys_rtc_info.appId;
      //   var appKey = "44689a25332aba3b8befd2acbbc88b79"; // 修改为自己的appkey 该方案仅为开发测试使用，正式上线需要使用服务端的AppServer
      var appKey = this.sys_rtc_info.appKey;
      var userId = this.user_info.id;
      var timestamp = parseInt(new Date().getTime() / 1000 + 48 * 60 * 60);
      var nonce = "AK-" + timestamp;
      var token = sha256(
        appId + appKey + channelId + userId + nonce + timestamp
      );
      return {
        appid: appId,
        userid: userId,
        timestamp: timestamp,
        nonce: nonce,
        token: token,
        gslb: ["https://rgslb.rtc.aliyuncs.com"],
        channel: channelId
      };
    },
    /**
     * 正在推流时,热切换进行republish操作
     */
    rePublish() {
      //计数
      if (this.publish_failed_time < 5) {
        aliWebrtc
          .publish()
          .then(res => {
            console.log("推流成功！", res);
            this.publish_failed_time = 0;
            setTimeout(() => {
              this.is_join_channel = true;
              this.getPublishState("success");
            }, 2000);
          })
          .catch(error => {
            console.log("推流失败！", error);
            this.publish_failed_time = this.publish_failed_time + 1;
            setTimeout(() => {
              this.rePublish();
              this.is_join_channel = false;
              this.getPublishState("danger");
            }, 2000);
          });
      } else {
        this.is_proccesing = false;
      }
    },
    /**
     * 订阅&取消订阅
     */
    unSub(v) {
      console.log("unsub参数", v);
      console.log("+++++++++++++++++++++++开始订阅+++++++++++++++++++++++");
      this.receivePublishManual(v).then(re => {
        console.log("订阅成功");
        this.updateUserList();
        this.creatDomAndshowRemoteVideo(v);
      });
      this.is_proccesing = false;
      // if (v.subscribed) {
      //   this.setConfigRemote(v.userId).then(re => {
      //     // this.removeDom(v.userId, v.label);
      //     console.log("取消订阅");
      //     this.updateUserList();
      //   });
      // } else {
      //   console.log("+++++++++++++++++++++++开始订阅+++++++++++++++++++++++");
      //   this.receivePublishManual(v).then(re => {
      //     console.log("订阅成功");
      //     this.updateUserList();
      //     this.creatDomAndshowRemoteVideo(v);
      //   });
      // }
    },
    /**
     * 获取当前remote用户的流菜单
     */
    showUserMenu(item, evt) {
      console.log("item:", item);
      let userId = item.userId;
      let userInfo = aliWebrtc.getUserInfo(userId);
      console.log("userInfo:", userInfo);
      let streamTypeList = userInfo.streamConfigs.filter(item => {
        return item.state === "active";
      });
      var html = "";
      if (streamTypeList.length == 0) {
        // this.$message.info("该用户未推流");
        console.log("该用户未推流");
        if (this.streamlist_failed_time < 5) {
          this.setTimeout(() => {
            this.showUserMenu(item, evt);
          }, 2000);
        } else {
          this.is_proccesing = false;
        }
      } else {
        this.streamlist_failed_time = 0;
        streamTypeList.map(item => {
          item.userId = userId;
          var labelName = "";
          if (item.type === "video") {
            switch (item.label) {
              case "sophon_video_camera_large":
                labelName = "视频流";
                break;
              case "sophon_video_screen_share":
                labelName = "共享流";
                break;
              case "sophon_audio":
                labelName = "";
                break;
              default:
                labelName = "";
            }
          } else {
            labelName = "";
          }
          //将音频流或小流的标签不显示
          this.unSub(item);
        });
      }
    },
    /**
     * 获取dom标签 设置video
     */
    creatDomAndshowRemoteVideo(v) {
      console.log(
        "——————————————————————————————渲染视频——————————————————————————————"
      );
      // var dom = this.getDisplayRemoteVideo(v.userId);
      var main_screen = this.getDisplayRemoteVideo("rtcVideo");
      var small_screen = this.getDisplayRemoteVideo("rtcShareVideo");
      try {
        if (main_screen.srcObject) {
          main_screen.srcObject = null;
        }
        if (small_screen.srcObject) {
          small_screen.srcObject = null;
        }
      } catch (error) {
        console.log("error:", error);
      }
      console.log("main_screen:", main_screen);
      console.log("small_screen:", small_screen);
      //存在共享流默认将共享流渲染到大屏
      if (this.is_share_screen) {
        if (v.label != "sophon_video_screen_share") {
          aliWebrtc.setDisplayRemoteVideo(v.userId, small_screen, 1);
        } else {
          aliWebrtc.setDisplayRemoteVideo(v.userId, main_screen, 2);
        }
      } else {
        if (v.label != "sophon_video_screen_share") {
          aliWebrtc.setDisplayRemoteVideo(v.userId, main_screen, 1);
        } else {
          aliWebrtc.setDisplayRemoteVideo(v.userId, small_screen, 2);
        }
      }
    },
    /**
     * 创建获取订阅的remote的video标签
     */

    getDisplayRemoteVideo(userId) {
      let video_dom = this.$refs[userId];
      // console.log("video_dom:", video_dom.length);
      if (video_dom && video_dom.length > 0) {
        return video_dom[0];
      } else {
        return video_dom;
      }
    },
    /**
     * 取消订阅设置
     */
    setConfigRemote(userId, label) {
      return new Promise((resolve, reject) => {
        //demo中只订阅大流
        if (label === "sophon_video_camera_large") {
          aliWebrtc.configRemoteCameraTrack(userId, false, false);
          aliWebrtc.configRemoteAudio(userId, false);
        } else if (label === "sophon_video_screen_share") {
          aliWebrtc.configRemoteScreenTrack(userId, false);
        }
        aliWebrtc
          .subscribe(userId)
          .then(re => {
            resolve();
          })
          .catch(error => console.log("取消订阅失败", error));
      });
    },
    /**
     * 订阅设置
     */
    receivePublishManual(v) {
      console.log("receivePublishManual订阅", v);
      return new Promise((resolve, reject) => {
        if (v.label === "sophon_video_camera_large") {
          console.log("订阅固定视频流");
          aliWebrtc.configRemoteCameraTrack(v.userId, true, true);
          aliWebrtc.configRemoteAudio(v.userId, true);
        } else if (v.label === "sophon_video_screen_share") {
          console.log("订阅屏幕共享流");
          aliWebrtc.configRemoteScreenTrack(v.userId, true);
        }
        aliWebrtc
          .subscribe(v.userId)
          .then(re => {
            resolve();
          })
          .catch(error => {
            reject(error);
            console.log("[subscribe失败]" + error.message);
            console.log(error);
          });
      });
    },
    handleStatus(type) {
      if (type == "play") {
        this.joinroom();
      } else if (type == "pause") {
        this.stopLive();
      }
    },
    async handleVolume(type) {
      let user_list = await aliWebrtc.getUserList();
      let observer;
      let admin_observer = user_list.filter(i => /admin/.test(i.userId));
      let teacher_observer = user_list.filter(
        i => i.userId == this.teacher_obj.id
      );
      //管理员开播订阅管理员 其次是课程老师
      if (admin_observer.length > 0) {
        observer = admin_observer ? admin_observer[0] : null;
      } else {
        observer = teacher_observer ? teacher_observer[0] : null;
      }
      console.log("observer:", observer);
      if (!observer) {
        if (this.is_mobile) {
          this.$toast("当前课程老师未开播！");
        } else {
          this.$Message.warning("当前课程老师未开播！");
        }
      } else {
        const { userId, streamConfigs } = observer;
        if (type == "up") {
          aliWebrtc.configRemoteCameraTrack(userId, true, true);
          aliWebrtc.configRemoteAudio(userId, true);
          aliWebrtc
            .subscribe(userId)
            .then(re => {
              console.log("取消订阅成功，", re);
              this.is_mute_volume = false;
            })
            .catch(error => console.log("取消订阅失败", error));
        } else if (type == "mute") {
          aliWebrtc.configRemoteCameraTrack(userId, true, true);
          aliWebrtc.configRemoteAudio(userId, false);
          aliWebrtc
            .subscribe(userId)
            .then(re => {
              console.log("取消订阅成功，", re);
              this.is_mute_volume = true;
            })
            .catch(error => console.log("取消订阅失败", error));
        }
      }
    },
    handleShowControls() {
      this.is_show_controls = true;
      this.debounce(() => {
        this.is_show_controls = false;
      }, 5000);
    },
    fullScreen(type) {
      let video = null;
      const element = document.documentElement;
      if (this.is_extend_subScreen) {
        video = this.$refs.rtcShareVideo;
      } else {
        video = this.$refs.rtcVideo;
      }
      if (type == "requestfull") {
        // //浏览器全屏
        // if (element.requestFullScreen) {
        //   element.requestFullScreen();
        // } else if (element.mozRequestFullScreen) {
        //   element.mozRequestFullScreen();
        // } else if (element.webkitRequestFullScreen) {
        //   element.webkitRequestFullScreen();
        // }
        //视频全屏
        if (video.requestFullscreen) {
          video.requestFullscreen();
        } else if (video.mozRequestFullScreen) {
          video.mozRequestFullScreen();
        } else if (video.webkitRequestFullScreen) {
          video.webkitRequestFullScreen();
        } else if (video.webkitEnterFullscreen) {
          // iOS进入全屏
          video.webkitEnterFullscreen();
        }
        if (this.is_ios) {
          this.onFullscreenChange();
        } else {
          video.addEventListener(
            "webkitfullscreenchange",
            this.onFullscreenChange,
            false
          );
          video.addEventListener(
            "fullscreenchange",
            this.onFullscreenChange,
            false
          );
        }
        this.is_full_screen = true;
      } else if (type == "exitfull") {
        // //退出浏览器全屏
        // if (document.exitFullscreen) {
        //   document.exitFullscreen();
        // } else if (document.msExitFullscreen) {
        //   document.msExitFullscreen();
        // } else if (document.mozCancelFullScreen) {
        //   document.mozCancelFullScreen();
        // } else if (document.webkitExitFullscreen) {
        //   document.webkitExitFullscreen();
        // }
        //退出视频全屏
        if (video.exitFullscreen) {
          video.exitFullscreen();
        } else if (video.mozCancelFullScreen) {
          video.mozCancelFullScreen();
        } else if (video.webkitCancelFullScreen) {
          video.webkitCancelFullScreen();
        }
        this.is_full_screen = false;
      }
    },
    onFullscreenChange(e) {
      console.log("监听视频全屏：", e);
      const video = this.$refs.rtcVideo;
      if (this.is_ios) {
        // 针对iOS监听不到webkitfullscreenchange事件做的兼容，感知退出全屏
        this.timer = setInterval(() => {
          if (!video.webkitDisplayingFullscreen) {
            // 退出了全屏
            clearInterval(this.timer);
            this.is_full_screen = false;
            video.play();
            video.removeEventListener(
              "webkitfullscreenchange",
              this.onFullscreenChange
            );
            video.removeEventListener(
              "fullscreenchange",
              this.onFullscreenChange
            );
          }
        }, 1000);
      } else {
        if (!video.webkitDisplayingFullscreen) {
          // 退出全屏
          this.is_full_screen = false;
          video.removeEventListener(
            "webkitfullscreenchange",
            this.onFullscreenChange
          );
          video.removeEventListener(
            "fullscreenchange",
            this.onFullscreenChange
          );
        }
      }
    },
    //防抖
    debounce(func, wait) {
      const _this = this;
      return !(function() {
        let context = this;
        let args = arguments;

        if (_this.timeout) clearTimeout(_this.timeout);

        _this.timeout = setTimeout(() => {
          func.apply(context, args);
        }, wait);
      })();
    },
    //屏幕交换
    exchangeScreen() {
      this.is_extend_subScreen = !this.is_extend_subScreen;
    }
  },
  created() {
    this.$nextTick(() => {
      if (process.client) {
        this.startRTC();
        window.onbeforeunload = function(e) {
          if (!aliWebrtc) {
            console.log("isSupport失败,未能初始化aliWebrtc", "danger");
            return;
          }
          aliWebrtc.leaveChannel();
          aliWebrtc.dispose();
        };
      }
    });
  },
  mounted() {}
};
